package com.cash.channel.svc.service.common;

import com.alibaba.fastjson.JSON;
import com.cash.channel.api.constant.Constant;
import com.cash.channel.api.model.ApiRequestModel;
import com.cash.channel.api.model.ApiResponseModel;
import com.cash.channel.api.model.request.RepayCalculateRequest;
import com.cash.channel.api.model.response.RepayCalculateResponse;
import com.cash.channel.svc.logic.RepayLogic;
import com.cash.channel.svc.model.ApplyWithdrawalFlow;
import com.cash.channel.svc.service.base.RepayCalculate;
import geex.core.service.LoanService;
import geex.core.service.SystemService;
import geex.core.service.model.loan.BookRepayAllResult;
import geex.core.service.model.loan.Loan;
import geex.core.service.model.repay.TryCalculateRepayAllResult;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
@Slf4j
@Service(Constant.CHANNEL.COMMON + Constant.SERVICE.提前结清试算)
public class CommonRepayCalculate implements RepayCalculate {

    @Autowired
    private LoanService loanService;

    @Autowired
    private RepayLogic repayLogic;


    @Autowired(required = false)
    private SystemService systemService;

    @Override
    public ApiResponseModel<RepayCalculateResponse> getRepayCalculate(ApiRequestModel apiRequestModel)  {
        try {
            RepayCalculateRequest repayCalculateRequest = JSON.parseObject(apiRequestModel.getData(), RepayCalculateRequest.class);
            String wdId = repayCalculateRequest.getWithdrawId();
            ApplyWithdrawalFlow applyWithdrawalFlow = repayLogic.getChannelByWdId(wdId);

            if(applyWithdrawalFlow==null){
                return new ApiResponseModel<>(false,-1,"未查询到对应订单号",null);
            }
            log.info("提前结清试算 tryCalculateRepayAll  wdId:" + wdId);
            Loan loan = loanService.findLoanByExtId(wdId);
            TryCalculateRepayAllResult res = loanService.tryCalculateRepayAll(loan.getLoanNo(), systemService.getSystemDate());
            log.info("提前结清试算 tryCalculateRepayAll  res:" + JSONObject.fromObject(res));
            if(!res.isSuccess()){
                return new ApiResponseModel<>(false, -1, res.getErrorMessage(), null);
            }
            RepayCalculateResponse response =new RepayCalculateResponse();
            BeanUtils.copyProperties(res, response);
            response.setPayTillTime(Constant.ProConstant.REPAY_TILL_TIME);
            return new ApiResponseModel<>(true, 0, "", response);

        }catch (Exception e){
            log.error(e.getMessage(), e);
            return new ApiResponseModel<>(false, -1, e.getMessage(), null);
        }
    }
}
